package com.zhida.jiyangcenter.address

import android.content.Intent
import android.os.Bundle
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import chooongg.http.HttpCallback
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIAccount
import com.zhida.jiyangcenter.api.AddressEntity
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.NetResponse
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.utils.SP
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.activity_address_list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@TitleBar(false)
@ContentLayout(R.layout.activity_address_list)
class AddressListActivity : BaseActivity() {
    val adapter = Adapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.title("收货地址")

        tv_address_commit.setOnClickListener {
            startActivity<AddAddressActivity> { }
        }
        rv_address_list.layoutManager = LinearLayoutManager(context)
        rv_address_list.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerBig)
                .colorResId(R.color.colorBack).build()
        )
        rv_address_list.setSwipeMenuCreator { leftMenu, rightMenu, position ->
            if (adapter.data[position].is_default == true) {
                rightMenu.addMenuItem(SwipeMenuItem(context).apply {
                    setBackgroundColorResource(R.color.colorPrimary)
                    setTextColorResource(R.color.white)
                    text = "取消默认"
                    width = dp2px(70f)
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                })
            } else {
                rightMenu.addMenuItem(SwipeMenuItem(context).apply {
                    setBackgroundColorResource(R.color.colorPrimary)
                    setTextColorResource(R.color.white)
                    text = "设为默认"
                    width = dp2px(70f)
                    height = ViewGroup.LayoutParams.MATCH_PARENT
                })
            }
            rightMenu.addMenuItem(SwipeMenuItem(context).apply {
                setBackgroundColorResource(R.color.color_333333)
                setTextColorResource(R.color.colorPrimary)
                text = "删除"
                width = dp2px(70f)
                height = ViewGroup.LayoutParams.MATCH_PARENT
            })
        }
        rv_address_list.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge.closeMenu()
            if (menuBridge.position == 0) {
                if (adapter.data[adapterPosition].is_default == true) {
                    lifecycleScope.request({
                        APIAccount.service().defaultCancel(
                            adapter.data[adapterPosition].uuid ?: ""
                        )
                    }, object : BaseAPI<Any>() {

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                        override fun onSuccess(t: Any?, state: Int, msg: String) {
                            tipSuccess(msg)
                            adapter.data[adapterPosition].is_default = false
                            adapter.notifyDataSetChanged()
                        }

                    })

                } else {
                    lifecycleScope.request({
                        APIAccount.service().defaultAddress(
                            adapter.data[adapterPosition].uuid ?: ""
                        )
                    }, object : BaseAPI<Any>() {

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }

                        override fun onSuccess(t: Any?, state: Int, msg: String) {
                            tipSuccess(msg)
                            adapter.data[adapterPosition].is_default = true
                            adapter.notifyDataSetChanged()
                        }

                    })
                }

            } else {
                lifecycleScope.request({
                    APIAccount.service().addressDelete(
                        adapter.data[adapterPosition].uuid ?: ""
                    )
                }, object : BaseAPI<Any>() {

                    override fun onError(e: APIException) {
                        tipFail(e.eMessage)
                    }

                    override fun onSuccess(t: Any?, state: Int, msg: String) {
                        adapter.remove(adapterPosition)
                        tipSuccess(msg)
                    }

                })

            }

        }
        rv_address_list.adapter = adapter
        adapter.setOnItemChildClickListener { _, view, position ->
            startActivity<AddAddressActivity> {
                putExtra("uuid", adapter.data[position].uuid)
            }
        }
        adapter.setOnItemClickListener { _, _, position ->
            if (intent.getStringExtra("type") == "confirm") {
                setResult(10, Intent().apply {
                    putExtra("uuid", adapter.data[position].uuid)
                    putExtra("name", adapter.data[position].name)
                    putExtra("phone", adapter.data[position].phone)
                    putExtra("area", adapter.data[position].area)
                    putExtra("detail", adapter.data[position].detail)
                })
                finish()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    private fun getData() {
        lifecycleScope.request({
            APIAccount.service().address()
        }, object : BaseAPI<List<AddressEntity>>() {

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }

            override fun onSuccess(t: List<AddressEntity>?, state: Int, msg: String) {
                adapter.setNewData(t)
            }

        })
    }

    class Adapter : BaseQuickAdapter<AddressEntity, BaseViewHolder>(R.layout.item_address_list) {
        override fun convert(helper: BaseViewHolder, item: AddressEntity?) {
            if (item?.is_default == true) {
                helper.setGone(R.id.check_box, true).setGone(R.id.tv_check_box, true)
            } else {
                helper.setGone(R.id.check_box, false).setGone(R.id.tv_check_box, false)
            }
            helper.setText(R.id.tv_address_item_name, item?.name)
                .setText(R.id.tv_address_item_phone, item?.phone)
                .setText(R.id.tv_address_item_details, item?.area + item?.detail)
                .addOnClickListener(R.id.tv_address_edit)
        }

    }
}